package com.lastproject.ejb.util;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.SurveyDTO;
import com.lastproject.ejb.entities.EmailGroup;
import com.lastproject.ejb.entities.Survey;

/**
 * Session Bean implementation class SurveyConversion
 */
@Stateless
@LocalBean
public class SurveyConversion {
	@PersistenceContext
	EntityManager em;
	
	@EJB
	EmailGroupConversion econv;

	public SurveyDTO fromEntity(Survey u) {

		SurveyDTO survey = new SurveyDTO();
		survey.setId(u.getId());
		survey.setDescription(u.getDescription());
		survey.setStartDate(u.getStartDate());
		survey.setEndDate(u.getEndDate());
		survey.setTitle(u.getTitle());
		survey.setIdUser(u.getUser().getId());
		survey.setIdTopic(u.getTopic().getId());
		if (u.getEmailGroup() != null)
			survey.setEmailGroup(econv.fromEntity(u.getEmailGroup()));
		return survey;
	}

	public Survey fromDTO(SurveyDTO u) {

		Survey survey = em.find(Survey.class, u.getId());

		if (survey == null) {
			survey = new Survey();
		}

		survey.setDescription(u.getDescription());
		survey.setStartDate(u.getStartDate());
		survey.setEndDate(u.getEndDate());
		survey.setTitle(u.getTitle());
		
		if (u.getEmailGroup() != null)
			survey.setEmailGroup(em.find(EmailGroup.class, u.getEmailGroup().getId()));
		
		return survey;
	}

}
